package com.leenmvc.core.utils.datasource;

import com.github.pagehelper.PageInterceptor;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.leenmvc.core.dao.communal.dataEntity.DataSourceFactory;
import com.leenmvc.core.dao.mysql.connect.DbConfig;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import java.beans.PropertyVetoException;
import java.util.Properties;

/**
 * 数据源操作工具类
 */
public class DBUtil {

    private final static Logger logger = LoggerFactory.getLogger(DBUtil.class);

    /**
     * 根据数据库参数构建数据源DataSource 以及 SqlSessionFactory
     *
     * @param dbConfig
     * @return
     */
    public static DataSourceFactory createDataSource(ConfigurableListableBeanFactory beanFactory,DbConfig dbConfig) {

        ComboPooledDataSource dataSource = DataSourceBuilder.create().type(ComboPooledDataSource.class).build();
        dataSource.setJdbcUrl(dbConfig.getJdbcUrl());
        dataSource.setUser(dbConfig.getUser());
        dataSource.setPassword(dbConfig.getPassword());
        try {
            dataSource.setDriverClass(dbConfig.getDriverClass());
        } catch (PropertyVetoException e) {
            logger.warn("设置驱动类错误：{}", e.getMessage());
        }
        dataSource.setMinPoolSize(dbConfig.getMinPoolSize());
        dataSource.setMaxPoolSize(dbConfig.getMaxPoolSize());
        dataSource.setMaxIdleTime(dbConfig.getMaxIdleTime());
        dataSource.setAcquireIncrement(dbConfig.getAcquireIncrement());
        dataSource.setMaxStatements(dbConfig.getMaxStatements());
        dataSource.setInitialPoolSize(dbConfig.getInitialPoolSize());
        dataSource.setIdleConnectionTestPeriod(dbConfig.getIdleConnectionTestPeriod());
        dataSource.setAcquireRetryAttempts(dbConfig.getAcquireRetryAttempts());
        dataSource.setAcquireRetryDelay(dbConfig.getAcquireRetryDelay());
        dataSource.setBreakAfterAcquireFailure(dbConfig.getBreakAfterAcquireFailure());
        dataSource.setTestConnectionOnCheckout(dbConfig.getTestConnectionOnCheckout());

        // 注册sqlSessionFactory
        SqlSessionFactoryBean sqlSessionFactoryBean = null;

        // 实例SessionFactory
        sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // 配置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);

        // 加载MyBatis配置文件
        PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

        Properties properties = new Properties();
        //数据库

        //是否分页合理化
        properties.setProperty("reasonable", "false");
        try {
            // 能加载多个，所以可以配置通配符(如：classpath*:mapper/**/*.xml)
            if (dbConfig.getJdbcUrl().contains("mysql")) {
                sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mapper/anshiiot/**/*.xml"));
                properties.setProperty("helperDialect", "mysql");
            } else {
                sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mapper/weight/**/*.xml"));
                properties.setProperty("helperDialect", "sqlserver");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        //分页插件
        Interceptor interceptor = new PageInterceptor();

        interceptor.setProperties(properties);
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{interceptor});
        try {
            // 设置自动驼峰命令转换，需要在最后设置
            sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);;
            return new DataSourceFactory(dataSource, sqlSessionFactoryBean.getObject());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

}
